import json

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Count
from django.http import Http404, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.views.decorators.csrf import csrf_exempt

from .models import BlogArticle, BlogCategory, BlogStats,BlogComment
from users.models import BlogUser

def right_sidebar_content():
    # 获取发表数量最多的博文作者列表前5名
    top_authors = BlogUser.objects.annotate(num_articles=Count('blogarticle')).order_by('-num_articles')[:5]
    #获取作者发布博文数量

    # 获取阅读排行榜，统计每篇博文的点击次数，并从多到少排序取前5名
    top_stats = BlogStats.objects.all().order_by('-counts')[:5]
    top_articles=[] 
    for index,item in enumerate(top_stats):         
         articles={}
         blog_article = BlogArticle.objects.get(title=item.blog)
         articles['id']=blog_article.id
         articles['title']=blog_article.title
         articles['counts']=item.counts
         top_articles.append(articles)
    # 获取博文类别
    categories = BlogCategory.objects.all()
    return top_authors,top_articles,categories

def index(request):
    # 获取博文列表数据
    blog_articles = BlogArticle.objects.all().order_by('-created_at')
    #加入分页处理
    # 创建分页器，每页显示10篇文章
    paginator = Paginator(blog_articles, 4)
    #  获取URL中的页码参数，如果没有则默认为第一页
    page = request.GET.get('page')
    try:
        articles = paginator.page(page)
    except PageNotAnInteger:
        # 如果 page 参数不是整数，则返回第一页
        articles = paginator.page(1)
    except EmptyPage:
        # 如果 page 参数超出范围，则返回最后一页
        articles = paginator.page(paginator.num_pages)
    # 右侧边栏数据
    top_authors,top_articles,categories = right_sidebar_content()
    # 组织传递给模板的数据字典对象
    context={
        'blog_articles': articles,
        'top_authors': top_authors,
        'top_articles':top_articles,
        'categories':categories
    }
    # 将博文数据传递给模板
    return render(request, 'index.html', context)

def search_blog_posts(request):
    #处理检索请求函数
    if request.method == 'POST':
        keyword = request.POST.get('keyword', '')
        if keyword:
            # 在所有博文中进行标题和内容的模糊匹配查询
            search_results = BlogArticle.objects.filter(title__icontains=keyword) | BlogArticle.objects.filter(content__icontains=keyword)
        else:
            search_results = None
    # 右侧边栏数据
    top_authors, top_articles, categories = right_sidebar_content()
    # 组织传递给模板的数据字典对象
    context = {
        'keyword':"以关键词 <span style='color:#f30'>"+keyword+"</span> 检索结果:",
        'search_results': search_results,
        'top_authors': top_authors,
        'top_articles': top_articles,
        'categories': categories
    }
    return render(request, 'search_results.html', context)

def get_blog_Author_Category(request):
    if request.method == 'GET':
        author = request.GET.get('author')
        category = request.GET.get('category')
        if author:
            blog_author = BlogUser.objects.get(username=author)
            search_results = BlogArticle.objects.filter(username=blog_author)
            keyword="作者 <span style='color:#f30'>"+author+"</span> 所有博文"
        elif category:
            blog_category = BlogCategory.objects.get(name=category)
            search_results = BlogArticle.objects.filter(category=blog_category)
            keyword="所有 <span style='color:#f30'>"+category+"</span> 类别博文:"
        # 右侧边栏数据
        top_authors, top_articles, categories = right_sidebar_content()
        # 组织传递给模板的数据字典对象
        context = {
            'keyword':keyword,
            'search_results': search_results,
            'top_authors': top_authors,
            'top_articles': top_articles,
            'categories': categories
        }
        return render(request, 'search_results.html', context)

def get_blog_detail_by_id(request, id):
    # 根据博文id获取博文详情
    try:
        #博文详情
        blog_detail = BlogArticle.objects.get(id=id)
        # 查询该博文的阅读统计对象
        blog_counts = BlogStats.objects.get(blog=blog_detail)
        # 如果找到了对应的阅读统计对象，则获取阅读数
        if blog_counts:
            views_count = blog_counts.counts
        else:
            views_count = 0  # 如果没有找到对应的阅读统计对象，则默认阅读数为0
        # 添加一次阅读次数
        blog_counts.counts=views_count+1
        # 更新该博文的阅读次数
        blog_counts.save()
        # 右侧边栏数据
        top_authors, top_articles, categories = right_sidebar_content()
        # 查询该博文的评论列表
        blog_comments=BlogComment.objects.filter(blog=blog_detail)
        # 组织传递给模板的数据字典对象
        context = {
            'article': blog_detail,
            'article_counts': views_count,
            'top_authors': top_authors,
            'top_articles': top_articles,
            'categories': categories,
            'comments':blog_comments
        }
        # 将博文数据传递给模板
        return render(request, 'blog_detail.html', context)
    except BlogArticle.DoesNotExist:
        raise Http404("博文不存在")

@csrf_exempt
def blog_submit(request):
    if request.method == 'POST':
        username = request.session['username']
        title = request.POST.get('title')
        content = request.POST.get('content')
        category = request.POST.get('category')
        if username and title and content:
            try:
                blog_user = BlogUser.objects.get(username=username)
                blog_category = BlogCategory.objects.get(name=category)
                article = BlogArticle.objects.create(
                    title=title,
                    content=content,
                    username=blog_user,
                    category=blog_category
                )
                article.save()
                stat = BlogStats.objects.create(
                    blog =article
                )
                stat.save()
                return JsonResponse({'message': 'successfully','code':1})
            except Exception as e:
                return JsonResponse({'error': str(e)}, status=400)
        else:
            return JsonResponse({'error': 'Username and password are required'}, status=400)
    else:
        return JsonResponse({'error': 'Only POST requests are allowed'}, status=405)

@csrf_exempt
def blog_modify(request):
    if request.method == 'POST':
        username = request.session['username']
        title = request.POST.get('title')
        content = request.POST.get('content')
        category = request.POST.get('category')
        if username and title and content:
            try:
                #获取两个关联外键对象
                blog_user = BlogUser.objects.get(username=username)
                blog_category = BlogCategory.objects.get(name=category)
                # 获取需要修改的博文对象
                article = get_object_or_404(BlogArticle, title=title, username=blog_user)
                article.title=title
                article.content=content
                article.category=blog_category
                article.save()
                return JsonResponse({'message': 'successfully','code':1})
            except Exception as e:
                return JsonResponse({'error': str(e)}, status=400)
        else:
            return JsonResponse({'error': 'Username and password are required'}, status=400)
    else:
        return JsonResponse({'error': 'Only POST requests are allowed'}, status=405)

@csrf_exempt
def blog_delete(request):
    if request.method == 'POST':
        username = request.session['username']
        id = request.POST.get('id')
        if username and id:
            try:
                #获取关联外键对象
                blog_user = BlogUser.objects.get(username=username)
                # 获取需要修改的博文对象
                article = get_object_or_404(BlogArticle, id=id, username=blog_user)
                # 删除操作
                article.delete()
                return JsonResponse({'message': 'successfully','code':1})
            except Exception as e:
                return JsonResponse({'error': str(e)}, status=400)
        else:
            return JsonResponse({'error': 'Username and password are required'}, status=400)
    else:
        return JsonResponse({'error': 'Only POST requests are allowed'}, status=405)

def blog_comment(request):
    if request.method == 'POST':
        commentor = request.POST.get('commentor')  #评论者
        blog = request.POST.get('blog')   #博文标题
        content = request.POST.get('comment')  #评论内容
        # 对内容进行过滤审核
        abnormals=["杀人","放火","色情","赌博","反动","诈骗","政府"]
        for word in abnormals:
            if word in content:
            # 如果发现不当言论，返回审核结果和处理建议
                return JsonResponse({'status': 'rejected', 'message': '内容包含不当言论，已被拒绝'})
        # 获取关联外键对象
        blog_user = BlogUser.objects.get(username=commentor)
        blog_article = BlogArticle.objects.get(title=blog)
        try:
            comments = BlogComment.objects.create(blog=blog_article,commentor=blog_user,content=content)
            return JsonResponse({'message': 'successfully', 'code': 1})
        except Exception as e:
            return JsonResponse({'error': str(e),'code':0}, status=400)


